#!/bin/bash
set -x
# This file has to write the entire env into the envfile
# Expects relative path to state folder it's supposed to restore as arg
# TODO: Clean this up, this looks/is ugly

export INPUT_FILENAME=$(realpath $1)

ENVFILE="envfile"
env | sort > $ENVFILE
pwd
# When running with afl-fuzz this script receives 198/199 as pipes for RPC with the forkserver.
# To forward these into the restored process we use --inherit-fd.
# The target for --inherit-fd within the restored process are the named pipes that are stored in the pipes file.
PIPE1=$(cat ./pipes | grep -o "pipe:\[.*\]" | head -n 1 )
PIPE2=$(cat ./pipes | grep -o "pipe:\[.*\]" | head -n 2 | tail -n 1 )

# echo "PIPE1:\"$PIPE1\""
# echo "PIPE2:\"$PIPE2\""

#echo "======="
#cp $INPUT_FILENAME /tmp
#ls -la
#echo $INPUT_FILENAME
#ls -la /proc/self/fd
#pwd
#echo $@
#echo "======="

echo -n "" > ./out/.cur_input

if [[ -z "$CRIU_SNAPSHOT_DIR" ]]; then
  CRIU_SNAPSHOT_DIR="./snapshot"
fi

## TEMPLATE ##

if [[ -z "${__AFL_SHM_ID}" ]]; then
  exec 198< /dev/null
  exec 199> /dev/null
  # We are in a snapshot run force PIDs out of the usual range.
  # 1<<15 is the largest that's legal on WSL2.
  echo "$((1<<15))" > /proc/sys/kernel/ns_last_pid
else
  echo "Running in AFL, no dummy FDs necessary"
fi

../criu/criu/criu restore -d \
    -vvv \
    -o ../restore.log \
    --images-dir $CRIU_SNAPSHOT_DIR \
    --inherit-fd "fd[198]:$PIPE1" \
    --inherit-fd "fd[199]:$PIPE2" \